// 定义完整的Tree类型
export interface Tree {
  id: number
  label: string
  children?: Tree[]
  flag?: 'entity'
  hidden?: boolean
  edit?: boolean // 补全缺失的edit属性
}

export const filterNodes = (nodes: Tree[]): Tree[] => {
  return nodes
    .filter((node) => !node.hidden)
    .map((node) => ({
      ...node,
      // 关键：子节点处理时也不复制，保持原始引用
      children: node.children ? filterNodes(node.children) : undefined,
    }))
}

// 递归查找节点
export const findNodeById = (treeData: Tree[], targetId: number): Tree | null => {
  for (const node of treeData) {
    if (node.id === targetId) return node
    if (node.children && node.children.length) {
      const found = findNodeById(node.children, targetId)
      if (found) return found
    }
  }
  return null
}

// 递归收集需要修改的节点
export const findNodesNeedToBeChange = (result: Tree[], treeData: Tree[]): void => {
  for (const node of treeData) {
    if (node.hidden) result.push(node)
    if (node.children && node.children.length) {
      findNodesNeedToBeChange(result, node.children)
    }
  }
}
